package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import com.example.farmrental.entity.UserEntity;
import com.example.farmrental.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单登录/注册接口（未接入Spring Security，前端本地存储登录态）
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    /** 用户名可用性检查 */
    @GetMapping("/check")
    public ResponseEntity<ApiResponse<Map<String, Boolean>>> check(@RequestParam String username){
        boolean exists = userRepository.existsByUsername(username);
        Map<String, Boolean> d = new HashMap<>();
        d.put("exists", exists);
        return ResponseEntity.ok(ApiResponse.success("检查成功", d));
    }

    /** 注册 */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<UserEntity>> register(@RequestBody Map<String, String> payload){
        String username = payload.get("username");
        String password = payload.get("password");
        String name = payload.get("name");
        String phone = payload.get("phone");
        if(username == null || username.isEmpty() || password == null || password.isEmpty()){
            return ResponseEntity.ok(ApiResponse.error("请提供用户名和密码", 400));
        }
        if(userRepository.existsByUsername(username)){
            return ResponseEntity.ok(ApiResponse.error("用户名已存在", 409));
        }
        UserEntity u = new UserEntity();
        u.setUsername(username);
        u.setPassword(password); // 简化：明文存储；实际应加密
        u.setName(name);
        u.setPhone(phone);
        u.setStatus(1);
        return ResponseEntity.ok(ApiResponse.success("注册成功", userRepository.save(u)));
    }

    /** 登录 */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@RequestBody Map<String, String> payload){
        String username = payload.get("username");
        String password = payload.get("password");
        UserEntity u = userRepository.findFirstByUsername(username);
        if(u == null || !u.getPassword().equals(password)){
            return ResponseEntity.ok(ApiResponse.error("用户名或密码错误", 401));
        }
        if(u.getStatus()!=null && u.getStatus()==0){
            return ResponseEntity.ok(ApiResponse.error("账号已停用", 403));
        }
        Map<String, Object> d = new HashMap<>();
        d.put("id", u.getId());
        d.put("name", u.getName());
        d.put("username", u.getUsername());
        return ResponseEntity.ok(ApiResponse.success("登录成功", d));
    }
}

